// @flow
import React from 'react'
import { Button } from 'antd'
import styles from './DevicePointer.css'
import Point from 'components/PointDevice'
import VarComp from 'components/VarCompDevice'
import Limits from 'components/LimitsDevice'
import universalFetch, { handleFetchError } from 'store/modules/fetch'

type Props = {
  form: Object,
  history: Array<any>,
  location: Object
}

type DevicePointerStates = {
  data: Object,
  specs: Array<any>,
  types: Array<any>,
  visiblePoint: boolean,
  visibleVariable: boolean,
  pointData: Array<any>,
  varData: Array<any>,
  confirmLoading: boolean,
  syncKmxVisible: boolean,
  limitsData: Array<Object>,
  monitorPointId: string,
  variableId: string
}
class DevicePointer extends React.Component {
  props: Props
  state: DevicePointerStates
  getPointData: Function
  getVarData: Function
  getPointVars: Function
  getSettingMenu: Function
  handleMenuClick: Function
  closeSyncKmxModal: Function
  getLimitsData: Function
  getVarLimits: Function
  goBack: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      data: this.props.location.state.data,
      specs: [],
      types: [],
      visiblePoint: false,
      visibleVariable: false,
      confirmLoading: false,
      pointData: [],
      varData: [],
      limitsData: [],
      syncKmxVisible: false,
      monitorPointId: '',
      variableId:''
    }
    this.getPointData = this.getPointData.bind(this)
    this.getVarData = this.getVarData.bind(this)
    this.getPointVars = this.getPointVars.bind(this)
    this.getLimitsData = this.getLimitsData.bind(this)
    this.getVarLimits = this.getVarLimits.bind(this)
    this.goBack = this.goBack.bind(this)
  }

  getData = () => {}
  goBack = () => {
    history.go(-1)
  }
  getPointData = () => {
    const { recordId } = this.props.location.state
    universalFetch(`${__SERVICE_API__}device/monitors/points?deviceId=${recordId}`)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.setState({
        pointData: json.result
      })
      // pointData = json.result
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }

  /**
   * [getSpecs description]
   * @param  {[type]} type [description]
   * @return {[type]}      [description]
   */
  // getSpecs (type: string) {
  //   this.setState({
  //     specs: getSpecs(type).map((d, i) => {
  //       return <Option key={d.id} value={d.value}>{d.label}</Option>
  //     })
  //   })
  // }

  /**
   * [handleTypeChange description]
   * @param  {[type]} value [description]
   * @return {[type]}       [description]
   */
  // handleTypeChange = (value: string) => {
  //   this.getSpecs(value)
  // }

  getVarData () {
    const { monitorPointId } = this.state
    const { location } = this.props
    const url = `${__SERVICE_API__}device/monitors/variables` +
      `?deviceId=${location.state.recordId}&monitorPointId=${monitorPointId}`
    universalFetch(url)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          varData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  getPointVars (point: Object) {
    const { location } = this.props
    const url = `${__SERVICE_API__}device/monitors/variables` +
      `?deviceId=${location.state.recordId}&monitorPointId=${point.id}`
    universalFetch(url)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          varData: json.result,
          monitorPointId: point.id
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  componentDidMount () {
    this.getData()
    this.getPointData()
    this.getVarData()
    this.getLimitsData()
  }

  getLimitsData () {
    const { recordId } = this.props.location.state
    const { monitorPointId, variableId } = this.state
    universalFetch(`${__SERVICE_API__}device/monitors/limits?deviceId=${recordId}` +
    `&variableId=${variableId}` +
    `&monitorPointId=${monitorPointId}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          limitsData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  getVarLimits (data: Object) {
    const { recordId } = this.props.location.state
    universalFetch(`${__SERVICE_API__}device/monitors/limits?deviceId=${recordId}` +
      `&variableId=${data.id}&monitorPointId=${data.monitorPointId}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          limitsData: json.result,
          variableId: data.id
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  render () {
    const { data, pointData, varData, limitsData } = this.state
    const { location } = this.props
    return (
      <div className={styles['main']}>
        <section className={styles['header']}>
          <div className={styles['header-title']}>
            <span>名称: </span>
            <span> {data.name}
            </span>
          </div>
          <div className={styles['header-content']}>
            <span>类型: {data.type}</span>
            <span>型号: {data.spec}</span>
          </div>
          <div className={styles['setting']} title='设置'>
            <Button onClick={this.goBack} className={styles['settingBtn']} >返回</Button>
          </div>
        </section>
        <Point {...{
          location,
          pointData,
          refreshPoint: this.getPointData,
          getPointVars: this.getPointVars
        }} />
        <VarComp {...{
          location,
          varData,
          pointData,
          refreshVar: this.getVarData,
          refreshLimit: this.getVarLimits
        }} />
        <Limits {...{
          limitsData,
          refreshLimit: this.getLimitsData
        }} />
      </div>
    )
  }
}

export default DevicePointer
